Remove Linked List Elements
LeetCode 203 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Example 1:

Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1
Output: []
Example 3:
Input: head = [7,7,7,7], val = 7
Output: []
Constraints:
- The number of nodes in the list is in the range `[0, 10^4]`.
- `1 <= Node.val <= 50`
- `0 <= val <= 50`
Topics: Linked List, Recursion
Approachβ
Linked Listβ
Use pointer manipulation. Common techniques: dummy head node to simplify edge cases, fast/slow pointers for cycle detection and middle finding, prev/curr/next pattern for reversal.
When to use
In-place list manipulation, cycle detection, merging lists, finding the k-th node.
Solutionsβ
Solution 1: C# (Best: 172 ms)β
| Metric | Value |
|---|---|
| Runtime | 172 ms |
| Memory | N/A |
| Date | 2017-09-22 |
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode RemoveElements(ListNode head, int val) {
if(head==null) return head;
ListNode dummy = new ListNode(Int32.MinValue);
dummy.next = head;
ListNode temp = head;
ListNode prev = dummy;
while (temp != null)
{
if (temp.val == val)
{
prev.next = temp.next;
temp = temp.next;
}
else { prev = temp; temp = temp.next; }
}
return dummy.next;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Linked List | $O(n)$ | $O(1)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Draw the pointer changes before coding. A dummy head node simplifies edge cases.